<template>
  <div>
    <upload_item @before-upload="imgHandleUpload" :file="imgFile" step="step 1" name="请上传图片"
                 :format="format1" v-if="!imgFile"></upload_item>
    <upload_item @before-upload="pyHandleUpload" :file="pyFile" step="step 2" name="请上传文件"
                 :format="format2" v-if="!pyFile"></upload_item>

    <div v-if="has_file">
      <ul class="onlineuploader-items-list">
        <li class="onlineuploader-item" v-if="imgFile">
          <Row>
            <Col span="1">
              <div class="onlineuploader-item-image ">
                <div class="image1">
                </div>
              </div>
            </Col>
            <Col span="6" class="column-title">
              <div>{{ file1.name }}</div>
              <span>{{ file1.size }}</span>
            </Col>
            <Col span="3" class="center">
              {{ file1.type }}
            </Col>

            <Col span="1" :offset="13" @click="closeimg">
              <div  class="wrong"></div>
            </Col>

          </Row>
        </li>
        <li class="onlineuploader-item" v-if="pyFile">
          <Row>
            <Col span="1">
              <div class="onlineuploader-item-image ">
                <div class="image2">
                </div>
              </div>
            </Col>
            <Col span="6" class="column-title">
              <div>{{ file2.name }}</div>
              <span>{{ file2.size }}</span>
            </Col>
            <Col span="3" class="center">
              {{ file2.type }}
            </Col>

            <Col span="1" :offset="13" @click="closepy">
              <div  class="wrong"></div>
            </Col>
          </Row>
        </li>
      </ul>
    </div>

    <Row>
      <Button class="up" @click="upload">
        点击上传
      </Button>
    </Row>


    <Modal v-model="modal1" draggable scrollable title="返回结果" ok-text="下载图片" @on-ok="download">
      <DescriptionList :col="1">
        <Description term="PSNR：">
          {{ psnr }}
        </Description>
        <Description term="SSIM：">
          {{ ssim }}
        </Description>

      </DescriptionList>
      <DescriptionList :col="1" layout="vertical">
        <Description term="原图(左) 隐写图(右): ">
          <Row :gutter="4">
            <Col span="12">
              <img
                  class="imgDisplay"
                  v-if="originImageLink"
                  :src="originImageLink"
                  alt=""
              />
            </Col>
            <Col span="12">
              <img
                  class="imgDisplay"
                  v-if="returnedImgLink"
                  :src="returnedImgLink"
                  alt=""
              />
            </Col>
          </Row>
        </Description>
      </DescriptionList>
    </Modal>

  </div>
</template>

<script>
import {encoder, decoder} from "@/api/encoder_decoder";
import {Col, DescriptionList} from "view-ui-plus";
import Upload_item from "@/components/upload_item";
// 加密
export default {
  name: "encryption",
  components: {Upload_item, DescriptionList},
  data() {
    return {
      format1:['jpg', 'jpeg', 'png'],
      format2:['py', 'txt'],
      has_file: false,
      file1: {},
      file2: {},
      modal1: false,
      isCollapsed: false,
      formItem: {},
      BASE_URL: "http://101.34.204.110:5000/static/",
      imgFile: null,
      pyFile: null,
      returnedImgLink: "https://java.jokerak.com/logo.jpg",
      originImageLink: "https://java.jokerak.com/logo.jpg",
      psnr: 1231,
      ssim: 98.54,
      loadingStatus: false,
      current: 0,
    };
  },

  methods: {
    handleFormatError(file, desc) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: 'File format of ' + file.name + ' is incorrect, please select ' + desc
      });
    },
    handleMaxSize(file, desc) {
      this.$Notice.warning({
        title: '文件大小超出范围',
        desc: 'File  ' + file.name + ' is too large, no more than ' + desc
      });
    },

    pyHandleUpload(pyFile) {
      if (!/\.(py|txt)$/.test(pyFile.name)) {
        this.handleFormatError(pyFile, "txt,py")
        return false;
      }
      if (pyFile.size > 1024 * 5) {
        this.handleMaxSize(pyFile, "5kb")
        return false;
      }
      this.pyFile = pyFile;
      this.file2 = {
        size: (pyFile.size / 1024).toFixed(2) + "kb",
        name: pyFile.name,
        type: pyFile.type
      }
      this.has_file = true
      return false;
    },


    imgHandleUpload(imgFile) {
      // 验证
      if (!/\.(jpg|jpeg|png)$/.test(imgFile.name)) {
        this.handleFormatError(imgFile, "jpg,png")
        return false;
      }
      if (imgFile.size > 1024 * 200) {
        this.handleMaxSize(imgFile, "200kb")
        return false;
      }
      this.imgFile = imgFile;
      this.file1 = {
        size: (imgFile.size / 1024).toFixed(2) + "kb",
        name: imgFile.name,
        type: imgFile.type
      }
      this.has_file = true
      return false;
    },
    closeimg(){
      this.imgFile=null
    },
    closepy(){
      this.pyFile=null
    },

    upload() {
      if (!this.imgFile) {
        this.$Notice.error({
          title: "请上传图片",
          desc: "加密需要图片和加密信息才能加密 ",
        });
        return;
      }
      if (!this.pyFile) {
        this.$Notice.error({
          title: "请上传加密信息",
          desc: "加密需要图片和加密信息才能加密 ",
        });
        return;
      }

      this.loadingStatus = true;
      this.$Spin.show();
      const that = this;
      encoder(this.imgFile, this.pyFile)
          .then((result) => {
            that.loadingStatus = false;
            that.imgFile = null;
            that.pyFile = null;
            this.modal1 = true;
            console.log(result);
            that.returnedImgLink = that.BASE_URL + result.watermarked_image_path;
            that.originImageLink = that.BASE_URL + result.origin_image_path;
            var psnr = result.psnr + ''
            that.psnr = psnr.substring(0, psnr.indexOf(".") + 3);
            var ssim = result.ssim + ''
            that.ssim = ssim.substring(0, ssim.indexOf(".") + 3);
            that.$Spin.hide();
          })
          .catch((error) => {
            that.loadingStatus = false;
            console.log(error);
            that.$Spin.hide();
          });
    },
    getUrlname(url) { //假如传进来的url是 http://www.qq.com/index.html?name=joey 这里一共是有3个斜杠,如果我们想获取index.html
      url = url.split('?')[0];// 我们只要?号前的
      var urlSlashCount = url.split('/').length; // 统计有3斜杠
      return url.split('/')[urlSlashCount - 1].toLowerCase(); //获取数组最后一个
    },

    download() {
      // console.log("下载")
      var image = new Image();
      const name = this.getUrlname(this.returnedImgLink)
      image.setAttribute('crossOrigin', 'anonymous');
      image.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        var context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/jpeg"); //得到图片的base64编码数据
        var a = document.createElement("a"); // 生成一个a元素
        var event = new MouseEvent("click"); // 创建一个单击事件
        a.download = name || "photo"; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
      }
      image.src = this.returnedImgLink;
    }
  }
}
</script>

<style scoped>
.lay {
  width: 100%;
}

.sideFont {
  color: #9ea7b4;
  font-size: 12px;
}


.upload {
  /*min-height: 130px;*/
  height: 100%;
}

.ivu-upload-drag {
  height: 100%;
  min-height: 130px !important;
}


.onlineuploader-items-list {
  display: block;
  margin: 0px;
  padding: 0;
  list-style: none;
  /*border: 1px solid #ebeef1;*/
  cursor: pointer;
  box-shadow: 0 1px 2px 0 rgb(60 64 67 / 30%), 0 1px 3px 1px rgb(60 64 67 / 15%);
  border-radius: .625rem;
  border: 1px solid transparent;
  transition: box-shadow .4s, transform .4s;
}

.onlineuploader-items-list:hover {
  border: 1px solid #2b932f;
  transform: translateY(-2%);
}

.onlineuploader-item {
  position: relative;
  margin: 0;
  padding: 5px 16px 5px 22px;
  border-bottom: 1px solid #ebeef1;
  /*border-top: 1px solid #ebeef1;*/
}

.column-title {
  padding-left: 16px;
  padding-right: 16px;
  color: #555;
  overflow: hidden;
}

.column-title div {
  width: 100%;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  font-weight: 400;
  text-shadow: 0 1px 0 rgb(0 0 0 / 15%) !important;
}

.column-title span {
  font-size: 12px;
  color: #979fb8;
  opacity: 0.7;
  font-weight: 300;
}

.onlineuploader-item-image {
  display: flex;
  height: 100%;
  width: 100%;

}

.onlineuploader-item-image div {
  /*position: absolute;*/
  /*top: 0;*/
  /*left: 0;*/
  width: 32px;
  height: 32px;
  /*flex: 1;*/
  margin: auto;
  border-radius: 3px;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-position: center;
  /*box-shadow: 0 2px 5px 0 rgb(147 147 147 / 64%);*/
}



.image1 {
  background-image: url("../assets/JPG_1.svg");
}

.image2 {
  background-image: url("../assets/py.svg");
}

/*.up{*/
/*  width: 80%;*/
/*  margin: 20px auto;*/
/*}*/

.up {
  max-width: 300px;
  width: 300px;
  box-shadow: 0 0 0 0 rgb(232 76 61 / 70%);
  border-radius: 50px;
  background-color: #00944f;
  color: #fff;
  line-height: 44px;
  height: 44px;
  cursor: pointer;
  font-size: 20px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 0 20px;
  font-weight: 300;
  /*animation: PDFConvert 5s cubic-bezier(0.66, 0, 0, 1) infinite;*/
  animation-delay: 2s;
  text-align: center;
  margin: 20px auto 0;
}

.up:hover {
  animation: scale-out-click 0.4s
}

.show_row {
  width: 100%;
}

.imgDisplay {
  height: 100%;
  width: 100%;
  /*max-height:150px;*/
  /*max-width:150px;*/
}

.wrong {
  background-image: url("../assets/wrong.svg");
  background-repeat: no-repeat;
  background-size: 50% 50%;
  /*background-color: red;*/
  width: 100%;
  height: 100%;
  /*background: #259229;*/
  background-position: center;
}
.center{
  text-align: center;
  line-height: 100%;
  height: 100%;
}
</style>